<template>
	<view style="background:#f2f5fa;overflow: hidden;">
	
		<view class="biaodan-info">
			<view class="forms-item-title">
				<u--text :text="matchInput.formName" margin="20rpx 0 10rpx 5rpx"/>
				<!-- payType: "normal" -->
				<u-tag :text="matchInput.formType=='normal_from'?'普通报名':
				matchInput.formType=='member_form'?'会员报名':
				matchInput.formType=='team_form'?'团队报名':''" :type="
				matchInput.formType=='normal_from'?'primary':
				matchInput.formType=='member_form'?'error':
				matchInput.formType=='team_form'?'warning':''
				" plain plainFill  size="mini"/>
				
			</view> 
		</view>
		<view class="biaodan-info">
				<u--form labelPosition="left" 
				:model="model" 
				:rules="rules" 
				ref="uForm" 
				labelWidth="70">
				
					<u-form-item 
					:required="rules[item.fieldEnName][0].required" 
					:label="item.fieldName" 
					:prop="item.fieldEnName" 
					v-for="(item,index) in matchInput.formFields" 
					:key="index"
					@click="item.fieldType=='DatePicker'?riqiFocus():item.fieldType=='TimePicker'?timeFocus():''"
					>
						
						<!-- 输入框 -->
						<u--input v-model="model[item.fieldEnName]" v-if="item.fieldType=='Input'"/>
						<!-- 文本域 -->
						<u--textarea :count="true" maxlength="200" v-model="model[item.fieldEnName]" v-if="item.fieldType=='textarea'"/>
						<!-- 单选 -->
						<u-radio-group  v-model="model[item.fieldEnName]"  v-if="item.fieldType=='Radio'">
							<u-radio :customStyle="{marginRight: '8px'}"
							  v-for="(item1, index1) in radiolist" :key="index1"
							  :label="item1.data"
							  :name="item1.id" 
							  
							  />
						</u-radio-group>
						<!-- 多选 -->
						 <u-checkbox-group v-model="model[item.fieldEnName]"  v-if="item.fieldType=='Checkbox'">
						   <u-checkbox
							   :customStyle="{marginRight: '8px'}"
							   v-for="(item2, index2) in checkboxList"
							   :key="index2"
							   :label="item2.data"
							   :name="item2.id"
						   />
						</u-checkbox-group>
						<!-- 日期选择 -->
						
						<u--input disabled
						 v-model="model[item.fieldEnName]" v-if="item.fieldType=='DatePicker'"
						 style="border-bottom: 1px solid #ccc;"
						 />
						
						 <!-- 时间选择 -->
						 <input disabled 
						  v-model="model[item.fieldEnName]" v-if="item.fieldType=='TimePicker'"
						  style="border-bottom: 1px solid #ccc;"
						  />
						  <!-- 图片或视频上传 -->
						  
						
							
						  <u-upload ref="upLoad" v-if="item.fieldType=='upload_view'||item.fieldType=='upload'"
								:accept="JSON.parse(item.initialData).dataArr[0].data=='img'?'image':JSON.parse(item.initialData).dataArr[0].data=='video'?'video':'file'"
						  		:fileList="FileObj[`${item.fieldEnName}`]"
						  		@afterRead="afterRead"
								useBeforeRead 
								@oversize="oversize"
						  		@delete="deletePic"
						  		:name="item.fieldEnName"
						  		multiple
						  		:maxCount="3"
								:maxSize="item.size*1024*1024"
						  	>
							
							</u-upload>
						
					</u-form-item>
					
				</u--form>
				<u-button type="primary" text="确定" @click="submit"></u-button>
		</view>
		
		<!-- 日期弹框 -->
		<u-datetime-picker :close="datePickClose" @cancel="datePickClose" :show="datePickerShow" v-model="value1" mode="date" @confirm="datePickSub"/>
		<!-- 时间选择 -->
		<u-datetime-picker :close="timePickClose"  @cancel="timePickClose" :show="timePickerShow" v-model="value2" mode="time" @confirm="timePickSub"/>
		<view>
			
			
		</view>
	</view>
</template>

<script>
	import {mapActions} from 'vuex'
import upload from '../../uni_modules/uview-ui/libs/config/props/upload';
import {getSaishiField} from '@/api/saishi/saishi.js'
	export default {
		data() {
			return {
				FileObj:{},
				
				imgMaxSize:0,
				matchId:0,//saishi0, 
				formId:0,
				
				matchInput:{},
				//model1:{},
				model:{},//验证需要
				rules:{},
				radiolist:[],//单选数据
				checkboxList:[],//多选
				
				datePickerShow:false,//日期弹框
				value1: Number(new Date()),//日期值
				timePickerShow:false,//时间弹框
				value2:'',//日期值
			};
		},
	
		async onReady() {
			
			let res=await getSaishiField(this.formId)
			this.matchInput={...res.data.data}
			//console.log(this.matchInput.formFields)
			this.matchInput.formFields.forEach((it,index)=>{
				/**
				 * 字段限制
				*/
				let arr1=JSON.parse(it.restrictJson)
				//需验证的字段model
				let jsmodel='{"'+arr1.type+'":""}'
				Object.assign(this.model,JSON.parse('{"'+arr1.type+'":null}'))
				
				
				
				//有验证字段时
				if(!uni.$u.test.isEmpty(arr1.formatter)&&!uni.$u.test.isEmpty(arr1.type)){
					
					//是否必填
					let isRequir=arr1.formatter.isRequired=="0"?true:false
					if(it.fieldType=='Input'||it.fieldType=='textarea'){
						//字符长度
						let strLen=arr1.formatter.len==""?0:arr1.formatter.len
						let jsrules=``
						if(strLen>0){
							jsrules=`{"${arr1.type}":[
							{"type": "string","required": ${isRequir}, "message": "请输入${it.fieldName}","trigger":["blur","change"]},
							{"type": "string","max": ${strLen},"message": "长度不得超过 ${strLen}"}
							]}`
						}else{
							jsrules=`{"${arr1.type}":[
							{"type":"string","required": ${isRequir}, "message": "请输入${it.fieldName}","trigger":["blur","change"]}
							]}`
						}
						
						//将限制信息存放到this.rules
						Object.assign(this.rules, JSON.parse(jsrules));						
					}else if(it.fieldType=='upload'||it.fieldType=='upload_view'){
						//字符长度
						let strSize=arr1.formatter.size==""?0:arr1.formatter.size
						let jsrules=``
						if(strSize>0){
							jsrules=`{"${arr1.type}":[
							{"type":"array","required": ${isRequir}, "message": "请选择文件","trigger":["blur","change"]}
							
							]}`
						}else{
							jsrules=`{"${arr1.type}":[
							{"type":"array","required": ${isRequir}, "message": "请选择文件","trigger":["blur","change"]}
							
							]}`
						}
						
						//将限制信息存放到this.rules
						Object.assign(this.rules, JSON.parse(jsrules));	
					}else if(it.fieldType=='Radio'){
							let jsrules=`{"${arr1.type}":[
								{"type":"number","required": ${isRequir},"message":"选择","trigger": "change"}
							]}`
							Object.assign(this.rules, JSON.parse(jsrules));
						
						
						
					}else if(it.fieldType=='Checkbox'){
						let jsrules=`{"${arr1.type}":[
							{"type":"array","required": ${isRequir},"message":"选择","trigger": "change"}
						]}`
						Object.assign(this.rules, JSON.parse(jsrules));
					}else{
						
						let jsrules=`{"${arr1.type}":[
						{"type":"string","required": ${isRequir}, "message": "请输入${it.fieldName}","trigger":["blur","change"]}
						
						]}`
						Object.assign(this.rules, JSON.parse(jsrules));	
					}
					
				}
				
				/**
				 * 数据
				*/
				//单选
				if(it.fieldType=='Radio'){
					this.radiolist=JSON.parse(it.initialData).dataArr
					this.model[it.fieldEnName]=this.radiolist[0].id
				}
				//多选
				if(it.fieldType=='Checkbox'){
					
					let arr=[]
					this.checkboxList=JSON.parse(it.initialData).dataArr
					arr.push(this.checkboxList[0].id)
					this.model[it.fieldEnName]=arr
				}
				
				//上传视频或图片
				if(it.fieldType=='upload_view'||it.fieldType=='upload'){
					it.size=JSON.parse(it.restrictJson).formatter.size?JSON.parse(it.restrictJson).formatter.size:Number.MAX_VALUE
				}
				
			})   
			this.restUpLoad()
			if(!uni.$u.test.isEmpty(this.model)&&!uni.$u.test.isEmpty(this.rules)){
				
				this.model=JSON.parse(JSON.stringify(this.model))
				this.rules=JSON.parse(JSON.stringify(this.rules))
			
				//onReady 为uni-app支持的生命周期之一
				this.$refs.uForm.setRules(this.rules)
			}
		},
		onLoad(params){
			this.matchId=params.matchId
			this.formId=params.formId
		},
		
		


		
		
		methods:{
			...mapActions('m_saishi',['getSaishiIngInputAction','getSaishiSubmitAction','getSaishiFieldAction']),
			//隐藏软键盘
			hideKeyboard() {
				uni.hideKeyboard()
			},
			//日期表单获取焦点
			riqiFocus(){
				this.hideKeyboard()
				this.datePickerShow=true;
			},
			//时间选择
			timeFocus(){
				this.hideKeyboard()
				this.timePickerShow=true;
			},
			dateChange(e){
				
			},
			dateChange(e){
				
			},
			//关闭日期弹窗
			datePickClose(){
				this.datePickerShow=false;
			},
			//关闭时间弹窗
			timePickClose(){
				this.timePickerShow=false;
			},
		
			//点击日期弹窗确定
			datePickSub(e){
				this.matchInput.formFields.forEach(item=>{
					if(item.fieldType=='DatePicker'){
						this.$set(this.model,`${item.fieldEnName}`,uni.$u.timeFormat(e.value, 'yyyy年mm月dd日'))
						this.$refs.uForm.validateField(`${item.fieldEnName}`); 
						
					}
				})
				this.datePickClose()
			},
			//点击时间弹窗确定
			timePickSub(e){
				
				this.matchInput.formFields.forEach(item=>{
					if(item.fieldType=='TimePicker'){
						this.$set(this.model,`${item.fieldEnName}`,uni.$u.timeFormat(e.value, 'yyyy年mm月dd日'))
						this.$refs.uForm.validateField(`${item.fieldEnName}`); 
					}
				})
				this.timePickClose()
			},
			//路由跳转
			goPage(url,obj){
				if(this.$store.state.m_login.token.length==0) return  uni.$u.toast('请您先登录')
				uni.$u.route(url,obj);
			},
			
			//设置 FileObj
			async restUpLoad(){
				let res=await getSaishiField(this.formId)
				res.data.data.formFields.forEach((it,index)=>{
					if(it.fieldType=='upload_view'||it.fieldType=='upload'){
						this.FileObj[it.fieldEnName]=[]	
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this.FileObj[event.name].splice(event.index, 1)
			},
			//点击上传按钮[文件读取之前]
			async oversize(event){
				this.getSaishiFieldAction({formId:this.formId,success:res=>{
					this.matchInput={...res.data.data}
					let RulesUpLoad={}
					this.matchInput.formFields.forEach((it,index)=>{
						if(it.fieldType=='upload'||it.fieldType=='upload_view'){
							let arr2=JSON.parse(it.restrictJson)
							//字符长度
							let strLen=arr2.formatter.size==""?0:arr2.formatter.size
							let jsrules =`{"${arr2.type}":[
								{"max": ${strLen},"message": "长度不得超过 ${strLen}"}
								]}`
							Object.assign(RulesUpLoad,JSON.parse(jsrules))
						
							
						}
					})
					
					let maxSize=RulesUpLoad[event.name][0].max*1024*1024
					event.file.forEach(item=>{
					if(item.size>maxSize) return uni.$u.toast('文件不能超过'+RulesUpLoad[event.name][0].max+'M')
					})
				}
				})
					
				
			
			},
			//图片上传afterRead[文件读取后]
			async afterRead(event){
				//本地上传的图片文件
				let lists = [].concat(event.file)
				//存放到服务器的容器长度
				let fileListLen = this.FileObj[event.name].length
					
				//将本地文件信息传到容器中
				lists.map((item) => {
					this.FileObj[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFile(lists[i].url)
					let item = this.FileObj[event.name][fileListLen]
				
					this.FileObj[event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url:result.data.fileName
					}))
					fileListLen++
				}	
					this.FileObj={...this.FileObj}	//回显 
					
					this.$set(this.model,`${event.name}`,this.FileObj[event.name])
					this.$refs.uForm.validateField(`${event.name}`); 
					
			},
			
			
			uploadFile(data){
				return uni.$u.http.upload('/common/uploadCTOss',{filePath:data,name:'file' ,custom: {auth: true}})
			},
		
			
			
			
			
			submit(){
				
					this.$refs.uForm.validate().then(res => {
								uni.$u.toast('校验通过')
								this.getSaishiSubmitAction({data:{
										
										"applyJson":JSON.stringify(this.model),
										"formId": this.matchInput.formId,
										"matchId": this.matchInput.matchId,
										"phone": this.model['phone'],
										"trueName": this.model['trueName']
									},success:res=>{
										if(res.data.code==200){
											uni.$u.toast('报名成功')
											this.model={}
											this.restUpLoad()
											uni.$u.route({
												type:'switchTab',
												url: 'pages/index/index',
											})
										}
									}})
							}).catch(errors => {
								uni.$u.toast('校验失败')
							})
			/* 	 */
			}
		}
	}
</script>

<style lang="scss" scoped>
	.biaodan-info{padding:20rpx;background: #fff;margin: 20rpx;}
	.forms-item-title{display: flex;justify-content: space-between;align-items: flex-end;}
	.biaodan-wrap_date{border-bottom:1px solid #ccc;padding:0px 5px;flex:1;display: flex;align-items:center;
	
	}
	
	.biaodan-wrap_date input{flex:1;height:35px;margin-left:5px;font-weight: normal;font-isze:30rpx;}
</style>
